<template>
  <div class="data-import-container">
    <!-- 状态 1: 数据类型选择网格 -->
    <div v-if="!hasFiles" class="type-selection-view">
      <div class="view-header">
        <h2>导入数据</h2>
        <p class="subtitle">请选择要导入的数据类型</p>
      </div>
      
      <div class="types-grid">
        <el-card 
          v-for="(label, type) in dataTypes" 
          :key="type" 
          class="type-card" 
          shadow="hover"
          @click="selectFilesForType(type)"
        >
          <div class="card-content">
            <div class="icon-wrapper" :class="type">
              <el-icon :size="40">
                <component :is="getTypeIcon(type)" />
              </el-icon>
            </div>
            <h3>{{ label }}</h3>
            <el-button type="primary" plain round class="select-btn">
              选择文件
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 状态 2: 导入工作区 -->
    <div v-else class="import-workspace">
      <!-- 顶部工具栏 -->
      <div class="workspace-header">
        <div class="header-left">
          <el-button @click="resetImport" circle>
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <span class="current-type-label">{{ dataTypes[currentType] }}导入</span>
          <el-tag type="info" class="file-count-tag">{{ totalFiles }} 个文件</el-tag>        
        </div>
        <div class="header-right">
          <el-button @click="selectFilesForType(currentType)">
            <el-icon><Plus /></el-icon> 添加文件
          </el-button>
          <el-button @click="validateAllGroups" :disabled="!hasFiles">
            <el-icon><Check /></el-icon> 全部校对
          </el-button>
          <el-button type="primary" @click="importAll" :disabled="!hasValidGroups || importing" :loading="importing">
            <el-icon><Upload /></el-icon> 全部导入
          </el-button>
        </div>
      </div>

      <div class="workspace-content">
        <!-- 左侧：文件分组列表 -->
        <div class="groups-panel">
          <div class="panel-title">识别结果</div>
          <el-scrollbar>
            <div class="groups-list">
              <div 
                v-for="(group, key) in groups" 
                :key="key"
                class="group-item"
                :class="{ active: activeGroupKey === key }"
                @click="activeGroupKey = key"
              >
                <div class="group-header">
                  <span class="group-name">{{ getGroupIndex(key) }}</span>
                  <el-button
                    class="remove-group-btn"
                    circle
                    size="small"
                    type="danger"
                    @click.stop="removeGroup(key)"
                  >
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
                <div class="group-status">
                  <el-tag size="small" :type="getStatusType(group)">{{ getStatusText(group) }}</el-tag>
                </div>
                <div class="group-files">
                  <div class="file-name">
                    <el-icon><Document /></el-icon>
                    <span v-if="group.sheetName && group.sheetName !== 'CSV'">{{ group.sheetName }}</span>
                    <span v-else>{{ getFileName(group.filePath) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 右侧：映射配置区 -->
        <div class="mapping-panel">
          <div v-if="activeGroupKey" class="mapping-content">
            <div class="mapping-toolbar">
              <div class="template-info">
                <span>选择模版: </span>
                <el-select 
                  v-model="groups[activeGroupKey].selectedTemplateId" 
                  placeholder="请选择模版"
                  @change="applyTemplate(activeGroupKey, $event)"
                  style="width: 280px"
                  clearable
                >
                  <el-option
                    v-for="tpl in availableTemplates"
                    :key="tpl.id"
                    :label="tpl.name"
                    :value="tpl.id"
                  >
                    <span>{{ tpl.name }}</span>
                    <el-tag v-if="tpl.isSystem" type="primary" size="small" style="margin-left: 8px">系统</el-tag>
                    <el-tag v-else type="success" size="small" style="margin-left: 8px">自定义</el-tag>
                  </el-option>
                </el-select>
                <el-tag 
                  v-if="groups[activeGroupKey].matchScore" 
                  type="info" 
                  size="small"
                  style="margin-left: 8px"
                >
                  匹配度: {{ groups[activeGroupKey].matchScore }}%
                </el-tag>
              </div>
              <div class="mapping-actions">
                <el-button @click="validateGroup(activeGroupKey)">
                  <el-icon><Check /></el-icon> 校对数据
                </el-button>
                <el-button type="primary" @click="importSingleGroup(activeGroupKey)" :disabled="!hasValidMapping(activeGroupKey) || importing" :loading="importing">
                  <el-icon><Upload /></el-icon> 导入本组
                </el-button>
                <el-button @click="saveAsTemplate(activeGroupKey)" :disabled="!hasValidMapping(activeGroupKey)">
                  <el-icon><Collection /></el-icon> 保存模版
                </el-button>
              </div>
            </div>

            <div class="horizontal-mapping-table-wrapper">
              <table class="horizontal-mapping-table">
                <thead>
                  <!-- 第一行：原始文件列名 -->
                  <tr>
                    <th class="row-header">原始列名</th>
                    <th 
                      v-for="header in groups[activeGroupKey].headers" 
                      :key="header" 
                      class="field-header"
                    >
                      {{ header }}
                      <el-tag 
                        v-if="getSystemFieldForHeader(activeGroupKey, header)" 
                        size="small" 
                        type="success"
                        style="margin-left: 5px;"
                      >
                        {{ getSystemFieldForHeader(activeGroupKey, header) }}
                      </el-tag>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <!-- 第二行：映射到哪个系统字段 -->
                  <tr class="mapping-row">
                    <td class="row-header">映射为 ▼</td>
                    <td 
                      v-for="header in groups[activeGroupKey].headers" 
                      :key="header" 
                      class="mapping-cell"
                    >
                      <el-select 
                        :model-value="findMappedField(activeGroupKey, header)"
                        @update:model-value="(val) => updateMapping(activeGroupKey, header, val)"
                        placeholder="选择系统字段"
                        clearable
                        filterable
                        size="small"
                        class="mapping-select"
                      >
                        <el-option
                          v-for="field in getMappingData(activeGroupKey)"
                          :key="field.key"
                          :label="field.label + (field.required ? ' *' : '')"
                          :value="field.key"
                        />
                        <el-option label="★ 自定义列 (动态)" value="_custom_" />
                        <el-option label="★ 忽略此列" value="_ignore_" />
                      </el-select>
                    </td>
                  </tr>

                  <!-- 第三行开始：预览数据 (展示前 5 行) -->
                  <tr v-for="(rowIdx) in 5" :key="rowIdx" class="preview-row">
                    <td class="row-header">预览 {{ rowIdx }}</td>
                    <td 
                      v-for="header in groups[activeGroupKey].headers" 
                      :key="header" 
                      class="preview-cell"
                      :class="getHeaderClass(activeGroupKey, header)"
                    >
                      {{ getPreviewValueForHeader(activeGroupKey, header, rowIdx - 1) }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- Debug Info -->
            
          </div>
          <div v-else class="empty-mapping">
            <el-empty description="请选择左侧分组进行配置" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, toRaw, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElScrollbar } from 'element-plus'
import { 
  Money, Phone, Van, OfficeBuilding, House, 
  Ticket, Goods, Document, User,
  ArrowLeft, Plus, Upload, Close, Check, Collection, Switch
} from '@element-plus/icons-vue'
import { TemplateManager } from '@/utils/templateManager'
import { useCaseStore } from '@/stores/case'

// Inject from parent
const currentCase = inject('currentCase')
const currentCaseId = inject('currentCaseId')
const showCaseSwitcherFromParent = inject('showCaseSwitcher')

// Data Types Configuration
const dataTypes = {
  personal_info: '个人信息',
  bank: '银行流水',
  call: '通话记录',
  hotel: '住宿登记',
  house: '不动产登记',
  train: '铁路售票',
  flight: '飞机售票',
  company: '工商企业'
}

// State
const currentType = ref(null)
const groups = ref({})
const activeGroupKey = ref(null)
const loading = ref(false)
const importing = ref(false)
const selectingFile = ref(false) // 防止重复打开文件选择对话框
const route = useRoute()
const router = useRouter()
const caseStore = useCaseStore()
const currentCaseName = ref('未知案件')
const caseSwitcherVisible = ref(false)
const selectedCase = ref(null)

// Dynamic Field Definitions
const currentFieldDefinitions = ref([])

// Default fallback definitions (will be merged/overridden by schema)
const defaultFieldDefinitions = {
  bank: [
    { key: 'account_name', label: '客户名称' },
    { key: 'card_number', label: '卡号', required: true },
    { key: 'transaction_time', label: '交易时间', required: true },
    { key: 'amount', label: '交易金额', required: true },
    { key: 'balance', label: '余额' },
    { key: 'opponent_name', label: '对方户名' },
    { key: 'opponent_account', label: '对方账号' },
    { key: 'summary', label: '摘要/备注' },
    { key: 'transaction_type', label: '借贷标志' }
  ],
  call: [
    { key: 'phone_number', label: '本机号码', required: true },
    { key: 'call_time', label: '通话时间', required: true },
    { key: 'duration', label: '通话时长' },
    { key: 'other_number', label: '对方号码', required: true },
    { key: 'call_type', label: '呼叫类型' },
    { key: 'location', label: '通话地点' }
  ],
  personal_info: [
    { key: 'name', label: '姓名', required: true },
    { key: 'id_card', label: '身份证号', required: true },
    { key: 'gender', label: '性别' },
    { key: 'birth_date', label: '出生日期' },
    { key: 'ethnic', label: '民族' },
    { key: 'address', label: '户籍地址' },
    { key: 'phone', label: '联系电话' },
    { key: 'workplace', label: '工作单位' },
    { key: 'position', label: '职务' },
    { key: 'education', label: '学历' },
    { key: 'political_status', label: '政治面貌' }
  ]
}

// Load case info on mount
onMounted(async () => {
  const caseId = route.query.caseId
  if (caseId) {
    if (caseStore.cases.length === 0) {
      await caseStore.fetchCases()
    }
    const currentCase = caseStore.cases.find(c => c.id == caseId)
    if (currentCase) {
      currentCaseName.value = currentCase.case_name || currentCase.name || `案件 ${caseId}`
    }
  }
})

// Computed
const hasFiles = computed(() => Object.keys(groups.value).length > 0)
const totalFiles = computed(() => {
  return Object.values(groups.value).reduce((sum, g) => sum + g.files.length, 0)
})

const hasValidGroups = computed(() => {
  return Object.keys(groups.value).some(key => hasValidMapping(key))
})

const availableTemplates = computed(() => {
  const allTemplates = TemplateManager.getAllTemplates()
  return Object.values(allTemplates).filter(t => t.dataType === currentType.value)
})

// Methods
// Helper to map data type to table name
const getTableNameForType = (type) => {
  const map = {
    personal_info: 'personal_info',
    bank: 'bank_transactions',
    call: 'call_records',
    travel: 'travel_records',
    hotel: 'hotel_records',
    house: 'house_records',
    train: 'train_records',
    flight: 'flight_records',
    company: 'company_records'
  }
  return map[type] || type
}

// Fetch schema fields from backend
const fetchSchemaFields = async (type) => {
  if (!type) return
  
  // Set default first
  currentFieldDefinitions.value = defaultFieldDefinitions[type] || []
  
  if (!window.electronAPI || !window.electronAPI.schema) return

  try {
    const tableName = getTableNameForType(type)
    
    // Try case_ prefix first as that's what SchemaEngine uses for case tables
    let schema = await window.electronAPI.schema.getByName(`case_${tableName}`)
    
    if (!schema) {
      // Fallback to standard name
      schema = await window.electronAPI.schema.getByName(tableName)
    }
    
    if (schema && schema.fields && schema.fields.length > 0) {
      // Map schema fields to UI definition format
      // Filter out internal fields
      const internalFields = ['id', 'case_id', 'created_at', 'updated_at', 'extra_data'];
      
      const schemaFields = schema.fields
        .filter(f => !internalFields.includes(f.name))
        .map(f => ({
          key: f.name,
          label: f.displayName || f.name,
          required: f.required
        }));
      
      currentFieldDefinitions.value = schemaFields;
      console.log('[DataImport] Loaded dynamic schema fields:', schemaFields);
    } else {
      console.log('[DataImport] No dynamic schema found, using defaults')
    }
  } catch (error) {
    console.error('[DataImport] Failed to fetch schema fields:', error)
  }
}

const getTypeIcon = (type) => {
  const map = {
    personal_info: 'User',
    bank: 'Money',
    call: 'Phone',
    travel: 'Van',
    hotel: 'OfficeBuilding',
    house: 'House',
    train: 'Ticket',
    flight: 'Ticket',
    company: 'Goods'
  }
  return map[type] || 'Document'
}

const selectFilesForType = async (type) => {
  // 如果正在选择文件，则不执行操作
  if (selectingFile.value) {
    return
  }

  currentType.value = type
  // Fetch dynamic fields for this type
  await fetchSchemaFields(type)
  
  selectingFile.value = true // 设置选择文件状态为true

  if (!window.electronAPI) return

  try {
    const result = await window.electronAPI.file.selectImportFile({
      title: `导入${dataTypes[type]}`,
      filters: [{ name: '表格文件', extensions: ['xlsx', 'xls', 'csv'] }]
    })

    if (result && !result.canceled && result.filePaths && result.filePaths.length > 0) {
      processFiles(result.filePaths)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('选择文件失败: ' + error.message)
  } finally {
    // 无论成功与否，都要重置选择文件状态
    selectingFile.value = false
  }
}

const processFiles = async (filePaths) => {
  loading.value = true
  try {
    const rawSheets = await window.electronAPI.file.inspectFiles(filePaths)
    console.log('[DataImport] inspectFiles result:', rawSheets)

    for (const sheet of rawSheets) {
      if (sheet.error) continue

      // 使用文件路径和工作表名称创建唯一的分组键，而不是仅使用表头签名
      // 这样不同工作表的数据会被分成不同的分组
      const groupKey = `${sheet.filePath}__${sheet.sheetName || 'default'}`

      console.log('[DataImport] Processing sheet:', {
        groupKey: groupKey,
        filePath: sheet.filePath,
        sheetName: sheet.sheetName,
        headers: sheet.headers,
        previewDataLength: sheet.preview?.length,
        firstPreviewRow: sheet.preview?.[0]
      })

      // 检查是否已存在该工作表的分组
      if (!groups.value[groupKey]) {
        // New group based on file path and sheet name
        const template = TemplateManager.tryAutoMapFromTemplate(currentType.value, sheet.headers)

        // Generate mapping from template if found
        let mapping = {}
        let matchScore = 0

        if (template && template.mappings) {
           let matchedCount = 0
           for (const [systemField, originalField] of Object.entries(template.mappings)) {
             if (sheet.headers.includes(originalField)) {
               mapping[systemField] = originalField
               matchedCount++
             }
           }
           // Calculate match score
           matchScore = Math.round((matchedCount / Object.keys(template.mappings).length) * 100)
        }

        groups.value[groupKey] = {
          headers: sheet.headers,
          files: [sheet.filePath],
          sheetName: sheet.sheetName, // 添加工作表名称
          filePath: sheet.filePath, // 添加文件路径
          previewData: sheet.preview,
          mapping: mapping,
          customValues: {},
          templateName: template ? template.name : null,
          selectedTemplateId: template ? template.id : null,
          matchScore: matchScore > 0 ? matchScore : null,
          status: template ? 'matched' : 'pending'
        }


        if (!activeGroupKey.value) activeGroupKey.value = groupKey

      } else {
        // Existing group
        if (!groups.value[groupKey].files.includes(sheet.filePath)) {
          groups.value[groupKey].files.push(sheet.filePath)
        }
      }
    }
  } catch (error) {
    console.error('[DataImport] processFiles error:', error)
    ElMessage.error('文件解析失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const resetImport = () => {
  if (hasFiles.value) {
    ElMessageBox.confirm('确定要放弃当前导入吗？', '提示', {
      type: 'warning'
    }).then(() => {
      groups.value = {}
      currentType.value = null
      activeGroupKey.value = null
      currentFieldDefinitions.value = []
    }).catch(() => {})
  } else {
    currentType.value = null
    currentFieldDefinitions.value = []
  }
}

const removeGroup = (key) => {
  delete groups.value[key]
  if (activeGroupKey.value === key) {
    activeGroupKey.value = Object.keys(groups.value)[0] || null
  }
}

const getGroupIndex = (key) => {
  const group = groups.value[key]
  if (group && group.sheetName) {
    // 返回工作表名称，如果工作表名称存在
    const fileName = getFileName(group.filePath)
    return `${fileName} - ${group.sheetName}`
  } else {
    // 如果没有工作表名称（比如CSV文件），则返回索引
    return `结构组 ${Object.keys(groups.value).indexOf(key) + 1}`
  }
}

const getFileName = (path) => {
  return path.split(/[\\/]/).pop()
}

const getStatusType = (group) => {
  if (group.status === 'matched') return 'success'
  if (group.status === 'error') return 'danger'
  return 'warning'
}

const getStatusText = (group) => {
  const map = { matched: '已匹配', pending: '待配置', error: '错误' }
  return map[group.status] || group.status
}

const getMappingData = (groupKey) => {
  return currentFieldDefinitions.value
}

const getPreviewValue = (groupKey, fieldKey) => {
  const group = groups.value[groupKey]
  if (!group) return ''
  
  const mappedHeader = group.mapping[fieldKey]
  if (!mappedHeader) return '-'
  
  if (mappedHeader === '_custom_') {
    return group.customValues[fieldKey] || '(空)'
  }
  
  const headerIndex = group.headers.indexOf(mappedHeader)
  if (headerIndex === -1 || !group.previewData || !group.previewData[0]) return '-'
  
  return group.previewData[0][headerIndex]
}

const getPreviewValueNew = (groupKey, fieldKey, rowIndex) => {
  const group = groups.value[groupKey]
  if (!group) return ''
  
  const mappedHeader = group.mapping[fieldKey]
  if (!mappedHeader) return '-'
  
  if (mappedHeader === '_custom_') {
    return group.customValues[fieldKey] || '(空)'
  }
  
  if (!group.previewData || !group.previewData[rowIndex]) return '-'
  
  const value = group.previewData[rowIndex][mappedHeader]
  
  return value || '-'
}

// 新增：获取原始列对应的预览数据
const getPreviewValueForHeader = (groupKey, header, rowIndex) => {
  const group = groups.value[groupKey]
  if (!group || !group.previewData || !group.previewData[rowIndex]) return '-'
  return group.previewData[rowIndex][header] || '-'
}

// 新增：查找原始列映射到哪个系统字段
const findMappedField = (groupKey, header) => {
  const group = groups.value[groupKey]
  if (!group) return null
  
  // 遍历mapping对象，找到value等于header的key
  for (const [fieldKey, mappedHeader] of Object.entries(group.mapping)) {
    // 支持数组映射（多列合并）
    if (Array.isArray(mappedHeader)) {
      if (mappedHeader.includes(header)) {
        if (fieldKey.startsWith('_custom_')) {
          return '_custom_'
        }
        return fieldKey
      }
    } else if (mappedHeader === header) {
      // 如果是自定义列，返回 _custom_ 以便下拉框正确显示选中状态
      if (fieldKey.startsWith('_custom_')) {
        return '_custom_'
      }
      return fieldKey
    }
  }
  return null
}

// 新增：获取原始列对应的系统字段标签
const getSystemFieldForHeader = (groupKey, header) => {
  const fieldKey = findMappedField(groupKey, header)
  if (!fieldKey) return null
  
  const fields = currentFieldDefinitions.value
  const field = fields.find(f => f.key === fieldKey)
  return field ? field.label : null
}

// 新增：更新映射（从原始列到系统字段）
// 支持多列合并到同一个目标字段（如 日期列 + 时间列 -> transaction_time）
const updateMapping = (groupKey, header, fieldKey) => {
  const group = groups.value[groupKey]
  if (!group) return
  
  // 清除该header的旧映射
  for (const key of Object.keys(group.mapping)) {
    const value = group.mapping[key]
    if (value === header) {
      delete group.mapping[key]
    } else if (Array.isArray(value) && value.includes(header)) {
      // 从数组中移除该header
      group.mapping[key] = value.filter(h => h !== header)
      if (group.mapping[key].length === 0) {
        delete group.mapping[key]
      } else if (group.mapping[key].length === 1) {
        // 如果只剩一个，转回单值
        group.mapping[key] = group.mapping[key][0]
      }
    }
  }
  
  // 如果不是忽略，设置新映射
  if (fieldKey && fieldKey !== '_ignore_') {
    // 如果是自定义列，生成唯一的key
    if (fieldKey === '_custom_') {
      group.mapping[`_custom_${header}`] = header
    } else {
      // 检查该字段是否已有映射
      const existingMapping = group.mapping[fieldKey]
      if (existingMapping) {
        // 如果已有映射，转为数组（支持多列合并）
        if (Array.isArray(existingMapping)) {
          if (!existingMapping.includes(header)) {
            existingMapping.push(header)
          }
        } else {
          // 转为数组
          group.mapping[fieldKey] = [existingMapping, header]
        }
      } else {
        group.mapping[fieldKey] = header
      }
    }
  }
}

// 新增：获取列的样式类（绿色=已映射，红色=校验错误，无色=其他）
const getHeaderClass = (groupKey, header) => {
  const field = findMappedField(groupKey, header)
  
  if (field) {
    // 已映射 - 绿色
    return 'header-mapped'
  }
  
  return '' // 未映射 - 无颜色
}

// 新增：获取列的错误状态（用于校验后标记）
const getHeaderErrorClass = (groupKey, header) => {
  const group = groups.value[groupKey]
  if (!group || !group.validationErrors) return ''
  
  // 如果这一列有校验错误，返回错误类
  const field = findMappedField(groupKey, header)
  if (field && group.validationErrors[field]) {
    return 'header-error'
  }
  
  return ''
}

const hasValidMapping = (key) => {
  const group = groups.value[key]
  if (!group) return false
  const fields = currentFieldDefinitions.value
  return fields.filter(f => f.required).every(f => group.mapping[f.key])
}

const validateGroup = (key) => {
  if (hasValidMapping(key)) {
    groups.value[key].status = 'matched'
    ElMessage.success('校验通过')
  } else {
    ElMessage.warning('请完成所有必填字段的映射')
  }
}

const validateAllGroups = () => {
  let validCount = 0
  let invalidCount = 0
  
  for (const key of Object.keys(groups.value)) {
    if (hasValidMapping(key)) {
      groups.value[key].status = 'matched'
      validCount++
    } else {
      invalidCount++
    }
  }
  
  if (invalidCount === 0) {
    ElMessage.success(`全部校验通过！共 ${validCount} 个分组`)
  } else {
    ElMessage.warning(`校验完成：${validCount} 个通过，${invalidCount} 个需要完善`)
  }
}

const importSingleGroup = async (key) => {
  if (!hasValidMapping(key)) {
    ElMessage.warning('请先完成必填字段的映射')
    return
  }
  
  importing.value = true
  const caseId = route.query.caseId
  const group = groups.value[key]
  
  try {
    const rawMapping = toRaw(group.mapping)
    const rawCustomValues = toRaw(group.customValues)

    let totalImported = 0
    let totalDuplicate = 0
    let processedFiles = 0

    for (const filePath of group.files) {
      let result = await window.electronAPI.data.import({
        caseId,
        dataType: currentType.value,
        filePath,
        sourceFile: filePath,
        mapping: JSON.parse(JSON.stringify(rawMapping)),
        customValues: JSON.parse(JSON.stringify(rawCustomValues))
      })

      // 检查是否需要用户确认（文件已存在）
      if (result.needConfirm) {
        // 询问用户是否要强制重新导入
        const confirmResult = await ElMessageBox.confirm(
          result.message,
          '文件已存在',
          {
            confirmButtonText: '重新导入',
            cancelButtonText: '跳过',
            type: 'warning'
          }
        ).catch(() => 'cancel') // 用户取消操作时返回'cancel'

        if (confirmResult === 'confirm') {
          // 用户选择重新导入，使用forceImport选项
          result = await window.electronAPI.data.import({
            caseId,
            dataType: currentType.value,
            filePath,
            sourceFile: filePath,
            mapping: JSON.parse(JSON.stringify(rawMapping)),
            customValues: JSON.parse(JSON.stringify(rawCustomValues)),
            forceImport: true  // 强制导入，跳过文件级去重
          })
        } else {
          // 用户选择跳过，直接继续下一个文件
          continue
        }
      }

      if (result.success) {
        totalImported += result.importedCount || 0
        totalDuplicate += result.duplicateCount || 0
        processedFiles++
      } else {
        console.error('单个文件导入失败:', result)
        ElMessage.warning(`文件 ${getFileName(filePath)} 导入异常: ${result.message || '未知错误'}`)
      }
    }

    // 构建提示消息
    let message = `成功处理 ${processedFiles} 个文件`
    if (totalImported > 0) {
      message += `，共导入 ${totalImported} 条数据`
    }
    if (totalDuplicate > 0) {
      message += `，跳过重复数据 ${totalDuplicate} 条`
    }

    if (totalImported > 0 || totalDuplicate > 0) {
      ElMessage.success(message)
    } else if (processedFiles > 0) {
      ElMessage.info(`文件已处理但没有新数据导入`)
    }

    // Remove this group after successful import
    delete groups.value[key]
    if (activeGroupKey.value === key) {
      activeGroupKey.value = Object.keys(groups.value)[0] || null
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败: ' + error.message)
  } finally {
    importing.value = false
  }
}

const switchCase = () => {
  router.push('/cases')
}

// 新增：显示案件切换对话框
const showCaseSwitcher = async () => {
  if (caseStore.cases.length === 0) {
    await caseStore.fetchCases()
  }
  selectedCase.value = null
  caseSwitcherVisible.value = true
}

// 新增：选择案件
const handleCaseSelect = (row) => {
  selectedCase.value = row
}

// 应用选中的模板
const applyTemplate = (groupKey, templateId) => {
  const group = groups.value[groupKey]
  if (!group) return
  
  // 清空 selectedTemplateId 时清除所有映射
  if (!templateId) {
    group.mapping = {}
    group.templateName = null
    group.selectedTemplateId = null
    group.matchScore = null
    ElMessage.info('已清除模板映射')
    return
  }
  
  // 获取选中的模板
  const allTemplates = TemplateManager.getAllTemplates()
  const template = allTemplates[templateId]
  
  if (!template || !template.mappings) {
    ElMessage.error('模板数据无效')
    return
  }
  
  // 应用模板映射
  let mapping = {}
  let matchedCount = 0
  
  for (const [systemField, originalField] of Object.entries(template.mappings)) {
    if (group.headers.includes(originalField)) {
      mapping[systemField] = originalField
      matchedCount++
    }
  }
  
  // 计算匹配度
  const matchScore = Math.round((matchedCount / Object.keys(template.mappings).length) * 100)
  
  // 更新组信息
  group.mapping = mapping
  group.templateName = template.name
  group.selectedTemplateId = templateId
  group.matchScore = matchScore > 0 ? matchScore : null
  
  ElMessage.success(`已应用模板"${template.name}"，匹配度: ${matchScore}%`)
}

// 新增：确认切换案件
const confirmSwitchCase = () => {
  if (!selectedCase.value) return
  
  caseSwitcherVisible.value = false
  router.push({
    path: '/workbench/data-import',
    query: { caseId: selectedCase.value.id }
  })
  
  // 更新当前案件名称
  currentCaseName.value = selectedCase.value.case_name || selectedCase.value.name
}

// 新增：获取自定义值
const getCustomValue = (groupKey, header) => {
  const group = groups.value[groupKey]
  if (!group || !group.customValuesMap) return ''
  return group.customValuesMap[header] || ''
}

// 新增：更新自定义值
const updateCustomValue = (groupKey, header, value) => {
  const group = groups.value[groupKey]
  if (!group) return
  
  if (!group.customValuesMap) {
    group.customValuesMap = {}
  }
  
  group.customValuesMap[header] = value
}

const saveAsTemplate = async (key) => {
  try {
    const { value: templateName } = await ElMessageBox.prompt('请输入模板名称', '保存模板', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^.{1,50}$/,
      inputErrorMessage: '模板名称不能为空，且不超过50个字符'
    })

    const group = groups.value[key]

    // 使用TemplateManager保存模板
    const result = TemplateManager.saveUserTemplate(
      templateName,
      currentType.value,
      toRaw(group.mapping)  // 只保存映射关系，不需要保存自定义值
    )

    if (result.success) {
      ElMessage.success(`模板 "${templateName}" 保存成功！`)
    } else {
      ElMessage.error(`模板保存失败: ${result.message}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存模板失败:', error)
      ElMessage.error('保存模板失败: ' + error.message)
    }
  }
}

const importAll = async () => {
  importing.value = true
  const caseId = route.query.caseId
  
  try {
    let totalImported = 0
    let totalSkipped = 0
    let totalRows = 0
    let fileCount = 0
    
    console.log('[导入] 开始批量导入，案件ID:', caseId, '数据类型:', currentType.value)
    
    for (const key of Object.keys(groups.value)) {
      const group = groups.value[key]
      if (!hasValidMapping(key)) {
        console.log('[导入] 跳过分组（无有效映射）:', key)
        continue
      }
      
      // Use toRaw to remove Vue reactivity proxies before sending to IPC
      const rawMapping = toRaw(group.mapping)
      const rawCustomValues = toRaw(group.customValues)
      
      console.log('[导入] 分组映射:', rawMapping)
      console.log('[导入] 自定义值:', rawCustomValues)

      for (const filePath of group.files) {
        console.log('[导入] 开始导入文件:', filePath)
        try {
          const result = await window.electronAPI.data.import({
            caseId,
            dataType: currentType.value,
            filePath,
            sourceFile: filePath,
            mapping: JSON.parse(JSON.stringify(rawMapping)),
            customValues: JSON.parse(JSON.stringify(rawCustomValues))
          })
          
          console.log('[导入] 文件导入结果:', result)
          
          // 检查是否需要用户确认（文件已存在）
          if (result && result.needConfirm) {
            // 对于批量导入，我们可以跳过或询问
            // 这里我们选择跳过，不中断批量操作
            console.log('[导入] 跳过已存在文件:', result.message)
            continue
          }

          if (result && result.success) {
            totalImported += result.importedCount || 0
            totalSkipped += result.duplicateCount || 0
            totalRows += result.totalCount || 0
            fileCount++
          } else {
            console.error('[导入] 文件导入失败:', result)
            ElMessage.warning(`文件 ${filePath.split(/[\\\/]/).pop()} 导入失败: ${result?.message || '未知错误'}`)
          }
        } catch (fileError) {
          console.error('[导入] 文件导入异常:', fileError)
          ElMessage.warning(`文件 ${filePath.split(/[\\\/]/).pop()} 导入异常: ${fileError.message}`)
        }
      }
    }
    
    console.log('[导入] 导入完成 - 文件数:', fileCount, '总行数:', totalRows, '已导入:', totalImported, '已跳过:', totalSkipped)
    
    // 构建提示消息
    let message = `成功处理 ${fileCount} 个文件`
    if (totalImported > 0) {
      message += `，共导入 ${totalImported} 条数据`
    }
    if (totalSkipped > 0) {
      message += `，跳过重复数据 ${totalSkipped} 条`
    }

    if (totalImported > 0 || totalSkipped > 0) {
      ElMessage.success(message)
    } else if (fileCount > 0) {
      ElMessage.info(`文件已处理但没有新数据导入`)
    }
    groups.value = {}
    currentType.value = null
    
  } catch (error) {
    console.error('[导入失败]', error)
    ElMessage.error('导入失败: ' + error.message)
  } finally {
    importing.value = false
  }
}
</script>

<style scoped>
.data-import-container {
  height: 100%;
  background-color: #f5f7fa;
  padding: 20px;
}

/* Type Selection View */
.type-selection-view {
  max-width: 1200px;
  margin: 0 auto;
}

.view-header {
  margin-bottom: 30px;
  text-align: center;
}

.view-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.types-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.type-card {
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.type-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.icon-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  background: #f0f9ff;
  color: #409eff;
}

.icon-wrapper.bank { background: #e1f3d8; color: #67c23a; }
.icon-wrapper.call { background: #faecd8; color: #e6a23c; }
.icon-wrapper.travel { background: #fde2e2; color: #f56c6c; }

.card-content h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
}

.select-btn {
  width: 100%;
}

/* Import Workspace */
.import-workspace {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  overflow: hidden;
}

.workspace-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-center {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  justify-content: center;
}

.case-info-label {
  font-size: 14px;
  color: #606266;
}

.current-type-label {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.workspace-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.groups-panel {
  width: 280px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  background: #fcfcfc;
}

.panel-title {
  padding: 15px;
  font-weight: bold;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
}

.groups-list {
  padding: 10px;
}

.group-item {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
}

.group-item:hover {
  border-color: #c6e2ff;
}

.group-item.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.group-status {
  margin-bottom: 8px;
}

.group-name {
  font-weight: bold;
  font-size: 14px;
  flex: 1;
}

.file-name {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 2px;
}

.remove-group-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.group-item:hover .remove-group-btn {
  opacity: 1;
}

.mapping-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
}

.mapping-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.mapping-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.template-info {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.required-star {
  color: #f56c6c;
  margin-right: 4px;
}

.mapping-select {
  width: 100%;
}

/* 表格边框增强 */
.horizontal-mapping-table {
  border-collapse: collapse;
  border: 2px solid #d0d0d0; /* 加粗外边框 */
}

.horizontal-mapping-table th,
.horizontal-mapping-table td {
  border: 1px solid #d0d0d0; /* 加粗单元格边框 */
  padding: 10px;
}

/* 列状态颜色标识 - 只应用于tbody */
.horizontal-mapping-table tbody .header-mapped {
  background-color: #d4edda !important; /* 绿色背景 - 已映射 */
}

.horizontal-mapping-table tbody .header-error {
  background-color: #f8d7da !important; /* 更明显的红色背景 - 校验错误 */
}

/* 表头不应用颜色 */
.horizontal-mapping-table thead th {
  background-color: #f5f7fa;
  font-weight: bold;
}

.mapping-select.is-mapped :deep(.el-input__inner) {
  color: #67c23a;
  font-weight: bold;
}

.custom-value-input {
  margin-top: 5px;
}

.preview-text {
  color: #606266;
  font-size: 13px;
}

.debug-info {
  margin-top: 20px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.debug-content {
  font-size: 12px;
  font-family: monospace;
}

.debug-content p {
  margin: 5px 0;
  word-break: break-all;
}

.debug-content pre {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
  overflow: auto;
  max-height: 200px;
}

.empty-mapping {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.horizontal-mapping-table-wrapper {
  flex: 1;
  overflow: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.horizontal-mapping-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1000px; /* Ensure horizontal scroll */
}

.horizontal-mapping-table th,
.horizontal-mapping-table td {
  border: 1px solid #ebeef5;
  padding: 12px;
  text-align: left;
}

.horizontal-mapping-table th {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #606266;
  white-space: nowrap;
}

.row-header {
  background-color: #f9fafc;
  font-weight: bold;
  width: 100px;
  position: sticky;
  left: 0;
  z-index: 1;
  box-shadow: 2px 0 4px rgba(0,0,0,0.05);
}

.field-header {
  min-width: 150px;
}

.mapping-cell {
  background-color: #fff;
}

.preview-row:nth-child(even) {
  background-color: #fafafa;
}

.preview-cell {
  color: #606266;
  font-size: 13px;
  white-space: nowrap;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.custom-value-input {
  margin-top: 5px;
}
</style>
